<template>    
    <el-dialog
      :title="title"
      :visible.sync="visible"
      width="800px"
      :before-close="handleClose"
      class="announcement-edit-dialog"
    >
      <el-form :model="form" :rules="rules" ref="form" label-width="100px" label-position="right">
        <el-form-item label="用户名" prop="username">
          <el-input style="width: 500px" v-model="form.username" placeholder="请输入用户名"></el-input>
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input style="width: 500px" v-model="form.email" placeholder="请输入邮箱"></el-input>
        </el-form-item>
        
        <el-form-item label="性别" prop="sex">
            <el-radio-group v-model="form.sex">
                <el-radio :label="0">女</el-radio>
                <el-radio :label="1">男</el-radio>
            </el-radio-group>
        </el-form-item>

        <el-form-item label="角色" prop="position">
          <el-radio-group v-model="form.position">
              <el-radio  :label="0">业主</el-radio>
              <el-radio :disabled="user.position === 1"  :label="1">工作人员</el-radio>
              <el-radio :disabled="user.position === 1"  :label="2">超级管理员</el-radio>
              <el-radio :disabled="user.position === 1" :label="3">维修人员</el-radio>
              <el-radio  :label="4">普通用户</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item v-if="form.position === 0" label="用户房屋" prop="buildNameAndCodeArray">
          <el-transfer
            filterable
            :filter-method="filterMethod"
            filter-placeholder="请输入房屋"
            v-model="form.buildNameAndCodeArray"
            :data="data">
          </el-transfer>
        </el-form-item>
      </el-form>
      
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="submitForm('form')">确 定</el-button>
      </span>
    </el-dialog>
    
  </template>
  
  <script>
import { cloneDeep } from 'lodash';
import api from '@/api';


  export default {  
    props: {
      visible: {
        type: Boolean,
        default: false
      },
      formData: {
        type: Object,
        default: () => ({})
      },
      title:{
        type: String,
        default: '新增用户'
      },
      hostelBuildArray:{
        type: Array,
        default: () => []
      },
      user:{
        type: Object,
        default: () => {}
      },
    },
    computed: {
        data() {
            const data = [];
            const cities = this.hostelBuildArrayPop;
            cities.forEach(item => {
                data.push({
                    label: item.label,
                    key: item.value,
                });
            });
            return data;
        }
    },
    data() {
      return {
        filterMethod(query, item) {
          return item.label.indexOf(query) > -1;
        },

        form: {
            id:'',
            username:'',
            buildNameAndCode:"",
            buildNameAndCodeArray: [],
            buildId:'',
            position: 0,
            email:"",
            sex: 0,
        },
        hostelBuildArrayPop: [],
        rules: {
          username: [
            { required: true, message: '请输入用户名', trigger: 'blur' },
            { min: 3, max: 20, message: '用户名长度必须在 3 到 20 个字符之间', trigger: 'blur' }
          ],
          email: [
            { required: true, message: '请输入邮箱', trigger: 'blur' },
            { type: 'email', message: '请输入有效的邮箱地址', trigger: ['blur', 'change'] }
          ],
          buildNameAndCodeArray: [
            { required: () => this.form.position === 2, message: '请选择用户房屋', trigger: 'blur' }
          ]
        },
      }
    },
    methods: {
      submitForm(form) {
        this.$refs[form].validate((valid) => {
          if (valid) {
            if(!this.form.id){
              this.form.password = this.generateRandomID();
            }
            console.log(this.form.buildNameAndCodeArray)
            //处理buildNameAndCodeArray
            this.form.hostelIds = this.form.buildNameAndCodeArray.join(",");

            api.saveOrUpdateByUserId(this.form).then(res =>{
              if(res.type === 'error'){
                this.$message.error(res.message)
              }else if(res.data.code === 200){
                if(this.form.id){
                  this.handleClose()
                  this.$message({
                    message: '操作成功',
                    type: 'success'
                  });
                  location.reload();
                }else{
                  this.$message({
                    message: '操作成功',
                    type: 'success'
                  });
                  this.open(this.form.password)
                }
              }else{
                this.$message.error(res.data.message)
              }
            })
          } else {
            console.log(this.form+111)
            this.$message.error('请完善表单信息');
            return false;
          }
        });
      },

      //设置日期格式
      formatDate(date) {
          const year = date.getFullYear();
          const month = String(date.getMonth() + 1).padStart(2, '0');
          const day = String(date.getDate()).padStart(2, '0');
          return `${year}-${month}-${day}`;
      },
      open(password) {
        this.$confirm('新用户初始密码：'+ password +' , 请保存好', '提示', {
          confirmButtonText: '确定',
          type: 'warning'
        }).then(() => {
          this.handleClose()
          location.reload();
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          });          
        });
      },
       // 生成XX位随机字符串
    generateRandomID() {
      //characters 中的随机数范围可以在右侧数字、字母中定义
          const characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
          const idLength = 10; // 字符串长度 这里生成30位的
          
          let randomID = '';
          
        // 循环生成随机字符，长度由 idLength 决定
          for (let i = 0; i < idLength; i++) {

            // 生成一个随机索引，范围是 0 到 characters 数组的长度减 1
            const randomIndex = Math.floor(Math.random() * characters.length);

        // 根据随机索引从 characters 字符串中提取一个字符，并将其附加到 randomID 上
            randomID += characters.charAt(randomIndex);
          }
          
        // 返回生成的随机字符串
          return randomID;
    },

      handleClose() {
        // 手动清空表单
        this.form = {
            id:'',
            username:'',
            buildNameAndCode:"",
            buildNameAndCodeArray: [],
            buildId:'',
            position: 0,
            email:"",
            sex: 0,
        };
        // 重置表单验证状态
        this.$refs['form'].resetFields();
        this.$emit('updateFormData', {});
        this.$emit('update:visible', false);
        this.$emit('update:title', '新增用户');
        this.hostelBuildArrayPop = cloneDeep(this.hostelBuildArray)
      },
    },
    watch: {
        // 监听 formData 的变化
        formData: {
            handler(newVal) {
                if (newVal && Object.keys(newVal).length > 0) {
                    // 深拷贝 formData 并赋值给 ruleForm
                    this.form = cloneDeep(newVal);
                    if(this.form.buildNameAndCodeArray && this.form.buildNameAndCodeArray.length>0){
                       this.hostelBuildArrayPop = newVal.newHostelBuildArray
                    }
                }
            },
            immediate: true, // 立即执行一次
            deep: true, // 深度监听
        },
        hostelBuildArray: {
            handler(newVal) {
                if (newVal && Object.keys(newVal).length > 0) {
                    this.hostelBuildArrayPop = cloneDeep(newVal);
                }
            },
            immediate: true, // 立即执行一次
            deep: true, // 深度监听
        }
    },
  }
  </script>
  
  <style scoped>

  .announcement-edit-dialog >>> .el-dialog__body {
    padding: 20px 30px;
  }
  
  .editor-wrapper {
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    overflow: hidden;
  }
  
  .editor-toolbar {
    border-bottom: 1px solid #dcdfe6;
    background-color: #f5f7fa;
  }
  
  .editor-content {
    min-height: 300px;
    max-height: 500px;
    overflow-y: auto;
  }
  
  .editor-form-item >>> .el-form-item__content {
    line-height: normal;
  }
  
  .line {
    line-height: 36px;
    color: #909399;
  }
  </style>